/**
 * Created by xiongwei on 2017/5/6.
 */

const HttpService = {

    toQueryString(params) {
        if (typeof params === 'object') {
            const paramsArray = [];
            Object.keys(params).forEach(key => paramsArray.push(`${key}=${encodeURIComponent(params[key])}`));
            return paramsArray.join('&');
        }

        return params.toString();
    },

    /**
     * GET请求
     * @param url
     * @param headers
     * @param params
     * @returns {*|Promise.<TResult>|Promise.<U>}
     */
    doGet(url, headers, params) {
        const queryString = this.toQueryString(params);
        if (url.search(/\?/) === -1) {
            url += `?${queryString}`;
        } else {
            url += `&${queryString}`;
        }
        return this.doFetch(url, 'GET', Object.assign({
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }, headers));
    },

    /**
     * REST形式的POST请求
     * @param url
     * @param headers
     * @param params
     * @returns {*|Promise.<TResult>|Promise.<U>}
     */
    doRestPost(url, headers, params) {
        return this.doFetch(url, 'POST', Object.assign({
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }, headers), params ? JSON.stringify(params) : params);
    },

    /**
     * 表单形式的POST请求
     * @param url
     * @param headers
     * @param params
     * @returns {*|Promise.<TResult>|Promise.<U>}
     */
    doFormPost(url, headers, params) {
        const paramsArray = [];
        if (params) {
            Object.keys(params).forEach(key => paramsArray.push(`${key}=${params[key]}`));
        }
        return this.doFetch(url, 'POST', Object.assign({
            'Content-Type': 'application/x-www-form-urlencoded',
        }, headers), paramsArray.join('&'));
    },

    /**
     * fetch
     * @param url
     * @param method
     * @param headers
     * @param body
     * @returns {*}
     */
    doFetch(url, method = 'GET', headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    }, body = undefined) {
        const options = {
            method,
            headers,
        };
        if (body) {
            options.body = body;
        }
        // LogService.debug(url, options);
        return fetch(url, options);
    },
};

export default HttpService;
